/**
 *  功能：测试WifiManager功能demo
 *  作者：单片机菜鸟
 *  时间：2019-12-13
 *  描述：
 *      1.启动wifimanager AP配置页面，通过手机连接esp8266生成的AP热点来进入设置页面
 *      2.请在手机浏览器上输入 192.168.4.25
 *      2.测试官方方法的使用
*/
 
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
 
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson
//for LED status
#include <Ticker.h>
 
void initSystem();
void initWifiManager();
void configModeCallback(WiFiManager *myWiFiManager);
void saveConfigCallback();
void tick();
 
//flag for saving data
bool shouldSaveConfig = false;
//for LED status
Ticker ticker;
 
//define your default values here, if there are different values in config.json, they are overwritten.
char mqtt_server[40];
char mqtt_port[6] = "8080";
char api_key[34] = "Your ApiKey";
 
void setup() {
  // put your setup code here, to run once:
  initSystem();
  initWifiManager();
  //if you get here you have connected to the WiFi
  Serial.println("connected...so easy :)");
  ticker.detach();
  //keep LED on
  digitalWrite(BUILTIN_LED, LOW);
}
 
void loop() {
  // put your main code here, to run repeatedly:
 
}
 
/**
 * 功能描述：初始化esp8266
 */
void initSystem(){
  Serial.begin(115200);
  Serial.println();
  //set led pin as output
  pinMode(BUILTIN_LED, OUTPUT);
  // start ticker with 0.5 because we start in AP mode and try to connect
  ticker.attach(0.6, tick);
}
 
/**
 * 功能描述：初始化wifimanager
 */
void initWifiManager(){
  /***  步骤一：创建 wifimanager对象 **/
  WiFiManager wifiManager;
  /*************************************/
  /*** 步骤二：进行一系列配置，参考配置类方法 **/
  // 重置保存的修改 目标是为了每次进来都是去掉配置页面
  wifiManager.resetSettings();
  // 配置连接超时
  wifiManager.setConnectTimeout(60);
  // 打印调试内容
  wifiManager.setDebugOutput(true);
  // 设置最小信号强度
  wifiManager.setMinimumSignalQuality(30);
  // 设置固定AP信息
  IPAddress _ip = IPAddress(192, 168, 4, 25);
  IPAddress _gw = IPAddress(192, 168, 4, 1);
  IPAddress _sn = IPAddress(255, 255, 255, 0);
  wifiManager.setAPStaticIPConfig(_ip, _gw, _sn);
  // 设置进入AP模式的回调
  wifiManager.setAPCallback(configModeCallback);
  // 设置点击保存的回调
  wifiManager.setSaveConfigCallback(saveConfigCallback);
  // 设置 如果配置错误的ssid或者密码 退出配置模式
  wifiManager.setBreakAfterConfig(true);
  // 设置过滤重复的AP 默认可以不用调用 这里只是示范
  wifiManager.setRemoveDuplicateAPs(true);
  // 添加额外的参数 博哥这里只是示范 比如加入 mqtt 服务器地址 port 端口号  apikey 后面可以结合onenet使用
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
  WiFiManagerParameter custom_apikey("apikey", "onenet apikey", api_key, 32);
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_apikey);
 
  /*************************************/
  /*** 步骤三：尝试连接网络，失败去到配置页面 **/
  // ssid 命名为danpianjicainiao pwd是123456
  if (!wifiManager.autoConnect("danpianjicainiao","123456")) {
      Serial.println("failed to connect and hit timeout");
      //reset and try again, or maybe put it to deep sleep
      ESP.reset();
      delay(1000);
  }
  /*************************************/
  // 读取配置页面配置好的信息
  strcpy(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(api_key, custom_apikey.getValue());
 
  // 保存自定义信息
  if (shouldSaveConfig) {
      Serial.println("saving config");
      DynamicJsonBuffer jsonBuffer;
      JsonObject& json = jsonBuffer.createObject();
      json["mqtt_server"] = mqtt_server;
      json["mqtt_port"] = mqtt_port;
      json["api_key"] = api_key;
      json.printTo(Serial);
      //end save
  }
 
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
}
 
/**
 * 功能描述：配置进入AP模式通知回调
 */
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
  //entered config mode, make led toggle faster
  ticker.attach(0.2, tick);
}
 
/**
 * 功能描述：设置点击保存的回调
 */
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}
 
/**
 * 功能描述：设置LED灯闪烁，提示用户进入配置模式
 */
void tick(){
  //toggle state
  int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO1 pin
  digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
}